//
//  ViewController2.swift
//  BankOfChina
//
//  Created by mac on 2023/11/19.
//

import UIKit
import WebKit
import SnapKit

class ViewController2: UIViewController, WKNavigationDelegate {
    var time:String = ""
    var filePath:String = ""
    lazy var progressView:UIProgressView = {
       let progress = UIProgressView.init()
        progress.trackTintColor = UIColor.white
        progress.progressTintColor = UIColor(hex: "#E7514B")
        progress.progress = 0.01
        return progress
    }()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }
    @IBOutlet weak var loadingImageView: UIImageView!
    override func viewDidLoad() {
        super.viewDidLoad()
        self.makeInit()

        // Do any additional setup after loading the view.
    }
    
    @IBAction func popBack(_ sender: Any) {
        self.dismiss(animated: false)
    }
    //浏览器内核
    private lazy var webContainer:ODBWebViewContainer = {
        let webContainer = ODBWebViewContainer()
        return webContainer
    }()
    
 
    @IBOutlet weak var contentView: UIView!
    
    lazy var webView2:WKWebView = {
        let webView = WKWebView.init(frame: CGRect.zero, configuration: ODBWebViewConfiguration())
        webView.allowsBackForwardNavigationGestures = true
        webView.backgroundColor = UIColor.white
        webView.scrollView.bounces = false
        webView.navigationDelegate = self
        webView.scrollView.showsHorizontalScrollIndicator = false
        webView.scrollView.showsVerticalScrollIndicator = false
        return webView
    }()
    
    func makeInit(){
        self.bindViewModel()
        self.setupViews()
        self.updateLayoutConstraints()
        self.webView2.isHidden = true
    }
    
    func timeStampToStringDetail(_ timeStamp:String)->String {
       let string = NSString(string: timeStamp)
       let timeSta:TimeInterval = string.doubleValue
       let dfmatter = DateFormatter()
       dfmatter.dateFormat="yyyy-MM-dd HH:mm:ss"
       let date = Date(timeIntervalSince1970: timeSta)
       return dfmatter.string(from: date)
   }
    @IBOutlet weak var downloadLabel: UILabel!
    
    func getStamp()->Int{
       //获取当前时间戳
       let date = Date()
       let timeInterval:Int = Int(date.timeIntervalSince1970)
       return timeInterval
   }
    override var preferredStatusBarStyle: UIStatusBarStyle {
      return .default
    }
    func bindViewModel (){
        self.view.addSubview(self.progressView)
        self.progressView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(44)
            make.height.equalTo(1)
        }
        
 
        GCDTimer.start(1, 60) {isFinish,count,intTimeCount in
            if(intTimeCount == 2){
                self.loadingImageView.isHidden = true
                self.webView2.isHidden = false
            }
            self.progressView.progress = Float(0.55 * intTimeCount)
            if (self.progressView.progress > 0.65){
                self.progressView.isHidden = true
            }
        }
        
        self.view.backgroundColor = UIColor.clear
        self.edgesForExtendedLayout = UIRectEdge.bottom;
        self.view.backgroundColor = UIColor.white
        
        self.downloadLabel.isUserInteractionEnabled = true
        let tap = UITapGestureRecognizer.init(target: self, action: #selector(download))
        self.downloadLabel.addGestureRecognizer(tap)
        let after = getStamp() + Int(60 * 30)
        self.time = self.timeStampToStringDetail(String(after))
        
        if let pdf = Bundle.main.url(forResource: "人行征信报告-2023-11-17", withExtension: "pdf", subdirectory: nil, localization: nil) {
            if let data = try?Data(contentsOf: pdf){
                let list = self.time.components(separatedBy: " ")
                let filePaths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
                let path = filePaths.first!+"/"+"人行征信报告-"+(list.first ?? "")+".pdf"
                self.filePath = path
                print(path)
                do{try data.write(to: URL(fileURLWithPath: path))}catch{ print("r存入失败")}
                
                if(FileManager.default.fileExists(atPath: path)){
                    print("存在")
                }else{
                    print("不存在")
                }
             }
            
            let req = URLRequest(url: pdf)
            self.webView2.load(req)
        }
    }
    
 
    @IBAction func share(_ sender: Any) {
 
 
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
       
    }
    
    func updateLayoutConstraints(){
        self.webView2.snp.makeConstraints { (make) in
            make.edges.equalTo(self.contentView);
        }
 
    }
    
    func setupViews(){
        self.contentView.addSubview(self.webView2)
 
    }
    
    @objc func download(){
        if self.filePath.count > 0{
            let file = self.filePath
            let shareVC = UIActivityViewController(activityItems: [URL(fileURLWithPath: file)], applicationActivities: nil)
            self.present(shareVC, animated: true, completion: nil)
        }
    }
    
 


}
